//
//  ThemeViewController.m
//  Store
//
//  Created by Chuz NetTech on 17/4/14.
//  Copyright © 2017年 Chuz NetTech. All rights reserved.
//

#import "ThemeViewController.h"
#import "ThemeTableViewCell.h"
#import "BDUserModel.h"
#import "BDHomeModel.h"
#import "BDHomeTableViewCell.h"
#import "BDHomeDetailViewController.h"
#import "BDUserInfoViewController.h"
#import "BDForwardViewController.h"
#import <UMSocialCore/UMSocialCore.h>
#import <UShareUI/UShareUI.h>
#import "BDVIPViewController.h"
#import "BDPayViewController.h"
#import "PBViewController.h"

/****     frame    ****/
#define kFCScreenWidth  ([UIScreen mainScreen ].bounds.size.width)
#define kFCScreenHeight ([UIScreen mainScreen ].bounds.size.height)

@interface ThemeViewController ()<UITableViewDelegate,UITableViewDataSource, PBViewControllerDataSource, PBViewControllerDelegate>
{
    NSInteger _type;
    NSIndexPath *exchangeIndexPath;
    NSArray *showImagesArray;
    UIView *curClickView;
}
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *datasource;

@property (nonatomic, strong) UIButton *seletedButton;
@end

@implementation ThemeViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    [self layoutSubviews];
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        self.startPage = @"1";
        [self requestDatasource];
    }];
    self.tableView.mj_footer = [MJRefreshBackFooter footerWithRefreshingBlock:^{
        [self requestDatasource];
    }];
    [self requestDatasource];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
}

- (void)layoutSubviews{
    UIView *titleView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 44)];
    
    UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 2)];
    lineView.backgroundColor =KBDColorBlue;
    [titleView addSubview:lineView];
    
    CGFloat allWidth = 0;
    NSArray *titleArray = @[ASLocalizedString(@"解锁主题"), ASLocalizedString(@"收藏主题")];
    for (int i = 0; i < titleArray.count; i++) {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        [button setTitle:titleArray[i] forState:UIControlStateNormal];
        [button setTitleColor:[UIColor colorWithHexString:@"#767676"] forState:UIControlStateNormal];
        [button setTitleColor:[UIColor colorWithHexString:@"#ffffff"] forState:UIControlStateSelected];
        button.titleLabel.font = [UIFont systemFontOfSize:17];
        button.size = CGSizeMake([titleArray[0] widthWithFont:button.titleLabel.font] + 20, 44);
        button.left = allWidth;
        [titleView addSubview:button];
        allWidth = button.right;
        if (i == 0) {
            button.selected = YES;
            lineView.width = button.width;
            lineView.left = button.left;
            lineView.bottom = titleView.height;
            self.seletedButton = button;
            _type = i + 1;
        }
        [[button rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
            if (button.selected == YES) {
                return;
            }
            [UIView animateWithDuration:0.3 animations:^{
                lineView.left = button.left;
            } completion:^(BOOL finished) {
                self.seletedButton.selected = NO;
                button.selected = YES;
                self.seletedButton = button;
                _type = i + 1;
                self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
                    self.startPage = @"1";
                    [self requestDatasource];
                }];
                [self.tableView.mj_header beginRefreshing];
            }];
        }];
    }
    titleView.width = allWidth;
    self.navigationItem.titleView = titleView;
}

- (void)requestDatasource{
    NSString *url = [NSString stringWithFormat:@"%@posts?page=%@&size=%@&type=%@", KBDBaseURL, self.startPage, self.pageSize, @(_type)];
    NSString *headValid = [BDUserModel getHeaderValidation];
    RACSignal *signal = [[BDNetworkingServer yy_GET:url parameters:nil validation:headValid automaticProcessingError:YES] execute:nil];
    [signal subscribeNext:^(id  _Nullable x) {
        if ([self.tableView.mj_header isRefreshing]) {
            [self.datasource removeAllObjects];
            [self.tableView.mj_header endRefreshing];
        }
        if ([self.tableView.mj_footer isRefreshing]) {
            [self.tableView.mj_footer endRefreshing];
        }
        self.startPage = x[@"next_page"];
        self.isEnd = [x[@"is_end"] boolValue];
        [self.datasource addObjectsFromArray:[BDHomeModel mj_objectArrayWithKeyValuesArray:x[@"list"]]];
        [self.tableView reloadData];
        [self setTableiewFooterViewStateFor:self.tableView datasourceCount:self.datasource.count];
    }];
    
    [signal subscribeError:^(NSError * _Nullable error) {
        [self showErrorViewWithTapBlock:^{
            [self.tableView.mj_header beginRefreshing];
        }];
    }];
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.datasource.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (_type == 1) {
        ThemeTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"themeCell" forIndexPath:indexPath];
        [cell configeWithModel:self.datasource[indexPath.row] touchBlock:^{
            BDHomeModel *model = self.datasource[indexPath.row];
            BDHomeDetailViewController *commntVC = [[BDHomeDetailViewController alloc] init];
            commntVC.homeModel = model;
            commntVC.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:commntVC animated:YES];
        }];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }else{
        BDHomeTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"homeCell" forIndexPath:indexPath];
        __block BDHomeModel *model = self.datasource[indexPath.row];
        model.isDetail = NO;
        [cell configeWithModel:model avatarBlock:^{
            NSDateFormatter * formatter = [[NSDateFormatter alloc ] init];
            [formatter setDateFormat:@"YYYY-MM-dd hh:mm:ss.SSS"];
            // BDLog(ASLocalizedString(@"点击了头像按钮：%@"), [formatter stringFromDate:[NSDate date]]);
            BDUserInfoViewController *infoVC = [[BDUserInfoViewController alloc] initWithUserID:model.user.user_id isFollow:model.is_follow guanzhuBlock:^(BOOL isFollow) {
                model.is_follow = isFollow;
            }];
            [self.navigationController pushViewController:infoVC animated:YES];
        } allButtonBlock:^{
            model.isOpen = !model.isOpen;
            [self.tableView reloadData];
        } zanBlock:^(UIButton *button){
            // BDLog(ASLocalizedString(@"点赞按钮"));
            [MBManager showLoadingAlert:ASLocalizedString(@"请稍后")clickHidden:NO clickBlock:nil];
            NSString *url = [NSString stringWithFormat:@"%@post/%@/praise", KBDBaseURL, @(model.my_id)];
            NSDictionary *para = @{@"id":@(model.my_id)};
            NSString *headValid = [BDUserModel getHeaderValidation];
            RACSignal *signal = [[BDNetworkingServer yy_POST:url parameters:para validation:headValid automaticProcessingError:YES] execute:nil];
            
            [signal subscribeNext:^(id  _Nullable x) {
                [MBManager hideAlert];
                button.userInteractionEnabled = YES;
                button.selected = !button.selected;
                if (button.isSelected) {
                    model.praiseCount++;
                }else {
                    model.praiseCount--;
                }
                model.praise = button.selected;
                [self.tableView reloadData];
            }];
            [signal subscribeError:^(NSError * _Nullable error) {
//                [MBManager hideAlert];
                button.userInteractionEnabled = YES;
                [MBManager showBriefAlert:ASLocalizedString(@"点赞失败")clickHidden:NO clickBlock:nil];
            }];
        } forwardBlock:^{
            exchangeIndexPath = indexPath;
            BDForwardViewController *forwardVC = [[BDForwardViewController alloc] init];
            forwardVC.homeModel = model;
            forwardVC.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:forwardVC animated:YES];
        } pinglunBlock:^{
            exchangeIndexPath = indexPath;
            BDHomeDetailViewController *commntVC = [[BDHomeDetailViewController alloc] init];
            commntVC.homeModel = model;
            commntVC.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:commntVC animated:YES];
        } sharedBlock:^{
            // BDLog(ASLocalizedString(@"分享按钮"));
            //        [UMSocialUIManager setShareMenuViewDelegate:self];
            [UMSocialUIManager setPreDefinePlatforms:@[@(UMSocialPlatformType_WechatSession),@(UMSocialPlatformType_WechatTimeLine),@(UMSocialPlatformType_WechatFavorite)]];
            [UMSocialUIManager showShareMenuViewInWindowWithPlatformSelectionBlock:^(UMSocialPlatformType platformType, NSDictionary *userInfo) {
                // 根据获取的platformType确定所选平台进行下一步操作
                NSString *url = [NSString stringWithFormat:@"%@tool/shareData", KBDBaseURL];
                NSString *headValid = [BDUserModel getHeaderValidation];
                RACSignal *signal = [[BDNetworkingServer yy_GET:url parameters:nil validation:headValid automaticProcessingError:YES] execute:nil];
                
                [signal subscribeNext:^(id  _Nullable x) {
                    //创建分享消息对象
                    UMSocialMessageObject *messageObject = [UMSocialMessageObject messageObject];
                    
                    //创建网页内容对象
                    NSString *thumbURL = x[@"share_logo"];
                    NSString *title = x[@"share_title"];
                    NSString *descr = x[@"share_text"];
                    NSString *webUrl = x[@"share_url"];
                    UMShareWebpageObject *shareObject = [UMShareWebpageObject shareObjectWithTitle:title
                                                                                             descr:descr
                                                                                         thumImage:thumbURL];
                    //设置网页地址
                    shareObject.webpageUrl = webUrl;
                    
                    //分享消息对象设置分享内容对象
                    messageObject.shareObject = shareObject;
                    
                    //调用分享接口
                    [[UMSocialManager defaultManager] shareToPlatform:platformType messageObject:messageObject currentViewController:self completion:^(id data, NSError *error) {
                        if (error) {
                            UMSocialLogInfo(@"************Share fail with error %@*********",error);
                        }else{
                            if ([data isKindOfClass:[UMSocialShareResponse class]]) {
                                //                            UMSocialShareResponse *resp = data;
                                //                            //分享结果消息
                                //                            UMSocialLogInfo(@"response message is %@",resp.message);
                                //                            //第三方原始返回的数据
                                //                            UMSocialLogInfo(@"response originalResponse data is %@",resp.originalResponse);
                                //                            NSLog(ASLocalizedString(@"分享成功了"));
                                NSString *backUrl = [NSString stringWithFormat:@"%@post/%@/shared", KBDBaseURL, @(model.my_id)];
                                RACSignal *backSignal = [[BDNetworkingServer yy_POST:backUrl parameters:nil validation:headValid automaticProcessingError:YES] execute:nil];
                                [backSignal subscribeNext:^(id  _Nullable x) {
                                    model.sharedCount++;
                                    [self.tableView reloadData];
                                    [MBManager showBriefAlert:ASLocalizedString(@"分享成功")clickHidden:NO clickBlock:nil];
                                }];
                                [backSignal subscribeError:^(NSError * _Nullable error) {
                                    [MBManager showBriefAlert:ASLocalizedString(@"分享失败")clickHidden:NO clickBlock:nil];
                                }];
                            }else{
                                //                            UMSocialLogInfo(@"response data is %@",data);
                                [MBManager showBriefAlert:ASLocalizedString(@"分享失败")clickHidden:NO clickBlock:nil];
                            }
                        }
                    }];
                }];
                [signal subscribeError:^(NSError * _Nullable error) {
                    [MBManager showBriefAlert:ASLocalizedString(@"获取分享信息失败")clickHidden:NO clickBlock:nil];
                }];
            }];
        } merchantsBlock:^{
            if (model.free || (model.free == NO && model.isPurchase == YES)) {
                BDHomeDetailViewController *detailViewController = [[BDHomeDetailViewController alloc] init];
                detailViewController.hidesBottomBarWhenPushed = YES;
                if (model.haveShopInfo) {
                    detailViewController.homeModel = model;
                }else{
                    detailViewController.homeModel = model.repost;
                }
                [self.navigationController pushViewController:detailViewController animated:YES];
            }else{
                BOOL isControl = [[[NSUserDefaults standardUserDefaults] objectForKey:@"versionControl"] boolValue];
                BDUserModel *currentUser = [BDUserModel getCurrentUser];
                if (isControl == YES || currentUser.is_auth == NO) {
                    [[UIApplication sharedApplication].keyWindow alertWithTitle:ASLocalizedString(@"提示")message:ASLocalizedString(@"购买会员可以查看所有加密帖子，是否前往购买？")type:AlertTypeAlert cancleTitle:ASLocalizedString(@"取消")otherTitle:@[ASLocalizedString(@"好的")] clickBlock:^(NSInteger index) {
                        if (index == 1) {
                            BDVIPViewController *vipVC = [[BDVIPViewController alloc] init];
                            vipVC.hidesBottomBarWhenPushed = YES;
                            [self.navigationController pushViewController:vipVC animated:YES];
                        }
                    }];
                }else{
                    BDPayViewController *payVC = [[BDPayViewController alloc] initWithPaySuccessedBlock:^{
                        [MBManager showBriefAlert:ASLocalizedString(@"支付成功")clickHidden:NO clickBlock:nil];
                        model.purchase = @[@""];
                        [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
                    }];
                    payVC.productId = [NSString stringWithFormat:@"%@", @(model.my_id)];
                    payVC.price = [NSDecimalNumber decimalNumberWithDecimal:[@(model.price) decimalValue]];
                    payVC.payType = BDProductPayTypePost;
                    payVC.product = model;
                    payVC.hidesBottomBarWhenPushed = YES;
                    [self.navigationController pushViewController:payVC animated:YES];
                }
            }
        } imageClickBlock:^(NSInteger index, NSArray *imagesArray, UIView *clickView) {
            showImagesArray = imagesArray;
            PBViewController *pbViewController = [PBViewController new];
            pbViewController.pb_dataSource = self;
            pbViewController.pb_delegate = self;
            pbViewController.pb_startPage = index;
            curClickView = clickView;
            [self presentViewController:pbViewController animated:YES completion:nil];
        }];
        return cell;
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (_type == 1) {
        return 95 + 20;
    }else{
        BDHomeModel *model = self.datasource[indexPath.row];
        return model.cellHeight;
    }
}

#pragma mark ------------------------PBViewController代理---------------------------
- (NSInteger)numberOfPagesInViewController:(PBViewController *)viewController {
    return showImagesArray.count;
}

- (void)viewController:(PBViewController *)viewController presentImageView:(UIImageView *)imageView forPageAtIndex:(NSInteger)index progressHandler:(void (^)(NSInteger, NSInteger))progressHandler {
    
    UIImage *placeholder = [UIImage imageNamed:@"business_pic"];
    [imageView sd_setImageWithURL:[NSURL URLWithString:showImagesArray[index]]
                 placeholderImage:placeholder
                          options:0
                         progress:^(NSInteger receivedSize, NSInteger expectedSize, NSURL * _Nullable targetURL) {
                             
                         } completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
                             
                         }];
}

- (UIView *)thumbViewForPageAtIndex:(NSInteger)index {
    return curClickView;
}

- (void)viewController:(PBViewController *)viewController didSingleTapedPageAtIndex:(NSInteger)index presentedImage:(UIImage *)presentedImage {
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (UITableView *)tableView{
    if (!_tableView) {
        self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, kBDTopHeight, kFCScreenWidth, kFCScreenHeight - kBDTopHeight)];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.backgroundColor = [UIColor clearColor];
        [_tableView registerClass:[ThemeTableViewCell class] forCellReuseIdentifier:@"themeCell"];
        [_tableView registerClass:[BDHomeTableViewCell class] forCellReuseIdentifier:@"homeCell"];
        
        _tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
        [self.view addSubview:_tableView];
    }
    return _tableView;
}

- (NSMutableArray *)datasource{
    if (!_datasource) {
        self.datasource = [NSMutableArray array];
    }
    return _datasource;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
